﻿using AntdUI;
using PosClient.Job;
using PosClient.Service;
using PosClient.View.Login.ViewModel;
using PosClient.View.MainForm;
using PosClient.View.MainForm.ViewModel;
using ReactiveUI;
using Splat;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Interop;

namespace PosClient
{
    public partial class LoginView : BorderlessForm, IViewFor<LoginViewModel>
    {
        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (LoginViewModel)value;
        }

        public LoginViewModel ViewModel { get; set; }

        public LoginView()
        {
            InitializeComponent();
            //注册
            InitRegister();
            //加载
            InitLoad();
            //绑定
            InitBinding();
            //事件
            InitEvent();
        }

        private void InitRegister()
        {
            Locator.CurrentMutable.RegisterLazySingleton(() => new LoginViewModel(RxApp.MainThreadScheduler));
            Locator.CurrentMutable.RegisterLazySingleton(() => new JobManager());
        }

        private void InitLoad()
        {
            Globals.LoginForm = this;
            if (Globals.IsTopic)
            {
                //加载主题图标
                ThemeHelper.IconFillForm(this);
            }
        }

        private void InitBinding()
        {
            ViewModel = new LoginViewModel(RxApp.MainThreadScheduler);
            this.WhenActivated(d =>
            {
                this.Events().Load
                    .Do(x => ActiveControl = input_code)
                    .Subscribe()
                    .DisposeWith(d);

                this.input_code.Events().KeyDown
                    .Where(x => x.KeyData == Keys.Enter)
                    .Do(e => ActiveControl = input_password)
                    .Subscribe()
                    .DisposeWith(d);

                this.Events().KeyDown
                    .Where(x => x.KeyData == Keys.Escape)
                    .Do(e => this.Close())
                    .Subscribe()
                    .DisposeWith(d);

                this.Bind(ViewModel, vm => vm.Password, v => v.input_password.Text).DisposeWith(d);
                this.Bind(ViewModel, vm => vm.Username, v => v.input_code.Text).DisposeWith(d);

                this.input_password.Events().KeyDown
                    .Where(y => y.KeyData == Keys.Enter)
                    .Do(x =>
                    {
                        if (input_password.Focused && !pageHeader_title.Loading)
                        {
                            Login();
                        }
                    })
                    .Subscribe()
                    .DisposeWith(d);

                ViewModel.LoginCommand.Subscribe(result =>
                {
                    if (!result.Success)
                    {
                        var config = new Notification.Config(this, "登录", "登录失败:" + result.Message, TType.Error, TAlignFrom.TR);
                        AntdUI.Notification.open(config);
                        input_code.Focus();
                        input_password.Clear();
                        ActiveControl = input_code;
                    }
                    else
                    {
                        Locator.CurrentMutable.RegisterConstant(new MainViewModel(RxApp.MainThreadScheduler), typeof(MainViewModel));
                        Locator.CurrentMutable.RegisterLazySingleton(() => new MainView());

                        this.Hide();
                        MainView main = new MainView();
                        main.ShowDialog();
                    }
                }).DisposeWith(d);


                ViewModel.LoadingCommand.Subscribe(result =>
                {
                    if (!result.Success)
                    {
                        var config = new Notification.Config(this, "初始化", "初始化错误:" + result.Message, TType.Error, TAlignFrom.TR);
                        AntdUI.Notification.open(config);
                        pageHeader_title.Loading = false;
                        button_login.Loading = false;
                        button_login.Text = "登录";
                    }
                }).DisposeWith(d);

            });
        }

        private void InitEvent()
        {
            this.Shown += (s, e) =>
            {
                Loading();
            };

            button_login.Click += (s, e) =>
            {
                if (!pageHeader_title.Loading)
                {
                    Login();
                }
            };

            this.FormClosed += (s, e) =>
            {
                Application.Exit();
            };

            label_register.Click += (s, e) =>
            {

            };


            this.FormClosing += (s, e) =>
            {
                var dialog = MessageBox.Show("确定要退出系统？", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                e.Cancel = !(DialogResult.Yes == dialog);
            };

        }

        private async void Loading()
        {
            pageHeader_title.Loading = true;
            button_login.Loading = true;
            button_login.Text = "正在初始化";

            var loadTask = Task.Run(() =>
            {
                ViewModel.LoadingCommand.Execute().Subscribe();
            });

            await loadTask.ContinueWith(d =>
            {
                if (d.IsFaulted)//任务出错
                {
                    Logger.Default.Error(d.Exception.Message, d.Exception);
                    var config = new Notification.Config(this, "初始化提示", "初始化错误:" + d.Exception.Message, TType.Error, TAlignFrom.TR);
                    AntdUI.Notification.open(config);
                    pageHeader_title.Loading = false;
                }
                if (d.IsCompleted)//任务完成
                {
                    pageHeader_title.Loading = false;
                }
                button_login.Loading = false;
                button_login.Text = "登录";
            });
        }

        private async void Login()
        {
            var loginTask = Task.Run(() =>
            {
                ViewModel.LoginCommand.Execute().Subscribe();
            });

            await loginTask.ContinueWith(d =>
            {
                if (d.IsFaulted)//任务出错
                {
                    Logger.Default.Error(d.Exception.Message, d.Exception);
                    var config = new Notification.Config(this,"登录提示", "初始化错误:" + d.Exception.Message, TType.Error, TAlignFrom.TR);
                    AntdUI.Notification.open(config);
                    button_login.Loading = false;
                }
                if (d.IsCompleted)//任务完成
                {
                    button_login.Loading = false;
                }
            });
        }

    }
}
